﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Chisel.Core
{
	/// <summary>
	/// Base class for ui elements that wrap actors and provide additional functionality.
	/// </summary>
	/// <remarks>This control has it's own canvas (LocalCanvas) to arrange its chilren.</remarks>
	public abstract class Wrapper : UserControl
	{

		public Wrapper(Actor actor)
			: base()
		{
			Actor = actor;
			Actor.Loaded += new RoutedEventHandler(OnActorLoaded);

			LocalCanvas = new Canvas();
			Content = LocalCanvas;

			// attach events
			actor.Moved += new ActorEventHandler(OnActorMoved);
			actor.SelectionChanged += new ActorEventHandler(OnSelectionChanged);
			actor.Resized += new ActorEventHandler(OnActorResized);
		}

		protected virtual void OnActorLoaded(object sender, RoutedEventArgs e)
		{
			Actor.ParentCanvas.Children.Add(this);
		}

		private Actor _actor;
		/// <summary>
		/// The actor these controls belong to.
		/// </summary>
		public Actor Actor 
		{
			get { return _actor; }
			private set
			{
				_actor = value;
				_actor.MouseEnter += new MouseEventHandler(OnActorMouseEnter);
				_actor.MouseLeave += new MouseEventHandler(OnActorMouseLeave);
			}
		}

		/// <summary>
		/// The canvas used to layout the control panel relative to the actor.
		/// </summary>
		protected Canvas LocalCanvas { get; private set; }


		#region Layout

		/// <summary>
		/// Moves the wrapper to the given location.
		/// </summary>
		protected void MoveTo(double x, double y)
		{
			Canvas.SetLeft(this, x);
			Canvas.SetTop(this, y);
		}
		
		/// <summary>
		/// Recomputes the layout of the controls based on the actor position and size.
		/// </summary>
		protected abstract void ComputeLayout();

		#endregion


		#region Mouse Interaction

		/// <summary>
		/// Recomputes the layout after the actor moves.
		/// </summary>
		protected virtual void OnActorMoved(Actor actor)
		{
			ComputeLayout();
		}

		/// <summary>
		/// Recomputes the layout after the actor resizes.
		/// </summary>
		protected virtual void OnActorResized(Actor actor)
		{
			ComputeLayout();
		}

		/// <summary>
		/// Handles the actor's mouse enter event.
		/// </summary>
		protected virtual void OnActorMouseEnter(object sender, MouseEventArgs e)
		{
		}

		/// <summary>
		/// Handles the actor's mouse leave event.
		/// </summary>
		protected virtual void OnActorMouseLeave(object sender, MouseEventArgs e)
		{
		}

		#endregion


		#region Actor Selection

		/// <summary>
		/// Handles the actor's selection changed event.
		/// </summary>
		protected virtual void OnSelectionChanged(Actor actor)
		{
		}

		#endregion


	}
}
